package com.hmdp.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
        //查询缓存信息
        List<String> shopTypeListStr = stringRedisTemplate.opsForList().range("cache:shopType:all", 0, -1);

        //缓存存在，转换为List集合后返回
        if (shopTypeListStr != null && !shopTypeListStr.isEmpty()) {
            ArrayList<ShopType> shopTypeList = new ArrayList<>();
            for (String shopTypeStr : shopTypeListStr) {
                ShopType shopType = JSONUtil.toBean(shopTypeStr, ShopType.class);
                shopTypeList.add(shopType);
            }
            return Result.ok(shopTypeList);
        }
        //缓存不存在
        //查询数据库得到List
        List<ShopType> shopTypeList = query().list();
        //List为空返回报错
        if (ArrayUtil.isEmpty(shopTypeList)) return Result.fail("数据异常,shopType为null");
        //根据id遍历List存入缓存

        for (ShopType shopType : shopTypeList) {
            log.info(shopType.toString());
            String shopTypeStr = JSONUtil.toJsonStr(shopType);
            log.info(shopTypeStr);
            stringRedisTemplate.opsForList().rightPush("cache:shopType:all",shopTypeStr);
        }
        return Result.ok(shopTypeList);
    }
}
